<?php

namespace plugin\admin\app\service\v1;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use support\exception\BusinessException;

/**
 * 会员充值服务类
 **/
class UserRechargeService
{

    /**
     * 充值
     *
     * @param array $params
     * @param array $admin
     **/
    public static function recharge($params, $admin)
    {
        list($pay_type, $amount, $code, $code_data) = array_values($params);

        $db = Util::db();

        if ($pay_type == CommonConstant::PAYTYPE_CARD) {
            $card_list = $db->table('wa_v1_recharge_card')
                ->whereIn('code', $code_data)
                ->get();
            if ($card_list->isEmpty()) {
                throw new BusinessException('卡号不存在！');
            }

            $code_flip = array_flip($code_data);
            $error_data = [];
            $money = 0;
            $cardIds = [];
            $insertData = [];
            $date = date('Y-m-d H:i:s');
            foreach ($card_list as $key => $value) {
                if (array_key_exists($value->code, $code_flip)) {
                    unset($code_flip[$value->code]);
                }
                if ($value->status == CommonConstant::DEFAULT_1) {
                    $error_data[] = $value->code;
                } else {
                    $cardIds[] = $value->id;

                    $money = bcadd($money, $value->amount, 2);
                    $data['user_id'] = $admin['id'];
                    $data['user_name'] = $admin['username'];
                    $data['code'] = $value->code;
                    $data['pay_type'] = $pay_type;
                    $data['amount'] = $value->amount;
                    $data['payamount'] = $value->amount;
                    $data['status'] = CommonConstant::DEFAULT_1;
                    $data['paytime'] = $date;
                    $data['transaction_id'] = $pay_type . '1234567890';
                    $insertData[] = $data;
                }
            }
            if ($code_flip) {
                throw new BusinessException('卡号：' . implode(',', array_keys($code_flip)) . '不存在！');
            }
            if ($error_data) {
                throw new BusinessException('卡号：' . implode(',', $error_data) . '已失效！');
            }
            if (!$money) {
                throw new BusinessException('充值卡金额错误！');
            }

            $cardData = [];
            $cardData['status'] = CommonConstant::DEFAULT_1;
            $cardData['user_id'] = $admin['id'];
            $logData = [
                'admin_id' => $admin['id'],
                'admin_name' => $admin['username'],
                'user_id' => $admin['id'],
                'user_name' => $admin['username'],
                'type' => CommonConstant::MONEY_LOG_TYPE_3,
                'change_type' => CommonConstant::DEFAULT_10,
                'money' => $money,
                'memo' => '给【' . $admin['username'] . '】充值 ' . $money . ' 个金币',
            ];
            $db->transaction(function () use ($db, $cardIds, $insertData, $cardData, $logData) {
                $db->table('wa_v1_recharge_card')->whereIn('id', $cardIds)->update($cardData);
                $db->table('wa_v1_user_recharge')->insert($insertData);
                UserService::money($logData, $logData['user_id'], [], ['type' => 'recharge']);
            });
            return ['code' => 0, 'msg' => '充值成功', 'data' => []];
        } else {
            $orderNo = 'R' . get_order_sn();
            $data['user_id'] = $admin['id'];
            $data['user_name'] = $admin['username'];
            $data['code'] = $orderNo;
            $data['pay_type'] = $pay_type;
            $data['amount'] = $amount;
            $data['payamount'] = $amount;
            $id = $db->table('wa_v1_user_recharge')->insertGetId($data);

            // TODO 2025
//            $amount = 0.01;
            $app_type = $pay_type == CommonConstant::PAYTYPE_ALIPAY ? 'pc' : 'native';
            $subject = '充值金币订单';
            $result = PaymentService::pay($pay_type, $app_type, compact('orderNo', 'amount', 'subject'));
            $qr = $result;
            return ['code' => 0, 'msg' => '支付信息', 'data' => compact('id', 'pay_type', 'qr')];
        }
    }

    /**
     * 订单业务逻辑处理 R
     *
     * @param float $payamount 支付金额
     * @param float $out_trade_no 订单号
     * @param float $trade_no 交易单号
     * @return mixed
     **/
    public static function order_settle($payamount, $out_trade_no, $trade_no)
    {
        $db = Util::db();
        $order = $db->table('wa_v1_user_recharge')
            ->where('code', $out_trade_no)
            ->first();
        if (!$order) {
            return V(1, '订单不存在或已删除');
        }
        // TODO 2025
        if ($payamount != $order->payamount) {
            return V(1, '订单支付金额不一致');
        }
        if ($order->status != CommonConstant::DEFAULT_0) {
            return V(1, '非待支付状态无法支付');
        }

        $data['status'] = CommonConstant::DEFAULT_1;
        $data['paytime'] = date('Y-m-d H:i:s');
        $data['transaction_id'] = $trade_no;
        $logData = [
            'admin_id' => $order->user_id,
            'admin_name' => $order->user_name,
            'user_id' => $order->user_id,
            'user_name' => $order->user_name,
            'type' => CommonConstant::MONEY_LOG_TYPE_3,
            'change_type' => CommonConstant::DEFAULT_10,
            'money' => $order->amount,
            'memo' => '给【' . $order->user_name . '】充值 ' . $order->amount . ' 个金币',
        ];
        $db->transaction(function () use ($db, $order, $data, $logData) {
            $db->table('wa_v1_user_recharge')->where('id', $order->id)->update($data);
            UserService::money($logData, $logData['user_id'], [], ['type' => 'recharge']);
        });
        return V(0, '支付成功');
    }

    /**
     * 获取充值订单状态
     **/
    public static function getQueryRecharge($id)
    {
        $db = Util::db();
        $status = $db->table('wa_v1_user_recharge')
            ->where('id', $id)
            ->value('status');
        if (!$status) {
            throw new BusinessException('未支付');
        }
        return true;
    }

}
